package com.warm.thread.manager;


import com.warm.core.utils.SolonUtil;
import com.warm.thread.manager.factory.AsyncFactory;
import com.warm.thread.utils.Threads;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 异步任务管理器
 *
 * @author warm
 */
public class AsyncManager {

    /**
     * 异步操作任务调度线程池
     */
    private final ScheduledExecutorService executor = SolonUtil.getBean("scheduledExecutorService");

    /**
     * 单例模式
     */
    private AsyncManager() {
    }

    private static final AsyncManager me = new AsyncManager();

    public static AsyncManager me() {
        return me;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public static void execute(TimerTask task) {
        // 操作延迟10毫秒
        int OPERATE_DELAY_TIME = 10;
        me.executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 执行任务
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     */
    public static void executeRecord(final String username, final String status, final String message,
                              final Object... args) {
        TimerTask task = AsyncFactory.recordLogininfor(username, status, message, args);
        // 操作延迟10毫秒
        int OPERATE_DELAY_TIME = 10;
        me.executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown() {
        Threads.shutdownAndAwaitTermination(executor);
    }
}
